package com.jcsz.gulimall.member.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @className: GuliFeignConfig
 * @author: 一把Po吉他
 * @date: 2022/11/12 18:02
 * @version: 1.0
 **/
@Configuration
public class GuliFeignConfig {

    @Bean
    public RequestInterceptor getRequestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                // 1、RequestContextHolder 拿到刚进来的这个请求
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (requestAttributes != null) {
                    // 老请求
                    HttpServletRequest request = requestAttributes.getRequest();
                    if (request != null) {
                        System.out.println("RequestInterceptor:" + Thread.currentThread().getId());
                        // 同步请求。
                        String cookie = request.getHeader("Cookie");
                        // 给新请求同步了老请求的的cookie
                        template.header("Cookie", cookie);
                    }
                }

            }
        };
    }
}
